import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormlyFormOptions } from '@ngx-formly/core';
import { ApesModalRef, ApesModalService } from '@shared/apes/modal';
import { exists} from '../../../../utils/utils';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';

@Component({
  selector: 'add-panel',
  templateUrl: './addPanel.component.html',
})
export class AddPanelComponent implements OnInit {

  form: FormGroup;
  modelData: any = {};

  // 面板名称
  name = {
    key: 'name',
    type: 'input',
    templateOptions: {
      label: '名称',
      divCol: 24,
      lblCol: 6,
      inputCol: 18,
      required: true,
    },
  };

  // 面板描述
  description = {
    key: 'description',
    type: 'textarea',
    templateOptions: {
      label: '描述',
      rows: 2,
      divCol: 24,
      lblCol: 6,
      inputCol: 18,
    },
  };

  // 岗位权限
  post = {
    key: 'post',
    type: 'select',
    templateOptions: {
      multiple: 'true',
      label: '岗位权限',
      api: 'aut.post.findAll',
      domain: '{"filters":[{"field":"name","operator":"EQ","value":"\'{{value}}\'"},{"field":"name","operator":"LIKE","value":"\'{{value}}\'"}],"groups":[],"operator":"or"}',
      divCol: 24,
      lblCol: 6,
      inputCol: 18,
      required: true,
    },
  };

  // 人员权限
  user = {
    key: 'user',
    type: 'select',
    templateOptions: {
      multiple: 'true',
      label: '个人权限',
      api: 'aut.user.findAll',
      domain: '{"filters":[{"field":"name","operator":"EQ","value":"\'{{value}}\'"},{"field":"name","operator":"LIKE","value":"\'{{value}}\'"}],"groups":[],"operator":"or"}',
      divCol: 24,
      lblCol: 6,
      inputCol: 18,
      required: true,
    },
  };

  params: any;
  fields = [];

  options: FormlyFormOptions = {};

  dialogRef: any = '';

  constructor(private modal: ApesModalRef,
              private apiService: ApiService,
              private msg: ApesMessageService,
              private modalService: ApesModalService) {
  }

  ngOnInit() {
    this.form = new FormGroup({});
    this.modelData = {};
    this.params = this.modal['apesComponentParams'];
    let context = this.params['context'];
    if (exists(context)) {
      this.form.reset(context);
      for (let key in context) {
        this.modelData[key] = context[key];
      }
    }
    this.fields = [
      this.name,
      this.description,
      this.post,
      this.user
    ];
  }

  // 弹框
  openDialog(params: any, callback?: any, dialog?: any) {
    const openDialog = dialog ? dialog : AddPanelComponent;
    this.dialogRef = this.modalService.create({
      apesWidth: 400,
      apesVisible: true,
      apesClosable: false,
      apesTitle: params.title,
      apesContent: openDialog,
      apesComponentParams: params,
      apesFooter: null,
    });
    return this.dialogRef.afterClose.subscribe((result) => callback(result));
  }

  // 按钮
  onEvent() {
    if (this.params['editor'] == 'add' || this.params['editor'] == 'copy') {
      this.editorPanel('add');
    } else if (this.params['editor'] == 'edit') {
      this.editorPanel('edit');
    }
  }

  // 编辑面板
  editorPanel(state) {
    if (!this.checkPanel()) {
      return;
    }
    let api = '';
    let data = this.modelData;
    let post = [];
    let user = [];
    if (state == 'add') {
      api = 'bi.canvas.create';
    } else if (state == 'edit') {
      api = 'bi.canvas.update';
    }
    this.modelData['post'].forEach((res) => {
      post.push({ 'post': res });
    });
    this.modelData['user'].forEach((res) => {
      user.push({ 'user': res });
    });
    data['canvasPostPermits'] = post;
    data['canvasUserPermits'] = user;
    this.savePanel(api, data);
  }

  // 检验参数
  checkPanel(){
    let result = true;
    if (!this.modelData['name']) {
      this.msg.error( '用户名不能为空');
      result = false;
      return result;
    }

    if (this.modelData['post'].length == 0 && this.modelData['user'].length == 0) {
      // if (this.modelData['post'].length == 0){
        this.msg.error('岗位权限不能为空');
      // }
      // if (this.modelData['user'].length == 0){
      //   this.msg.error('个人权限不能为空');
      // }
      result = false;
      return result;
    }
    return result;
  }

  // 保存面板
  savePanel(api, data) {
    this.apiService.post(api, data).subscribe(() => {
      this.closePanelDialog();
    });
  }

  // 关闭面板弹框
  closePanelDialog() {
    this.modal.destroy(this.modelData);
  }

}
